package Observer_pattern;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

/**
 * Created with IntelliJ IDEA.
 * User: Bjarke
 * Date: 14-10-13
 * Time: 19:28
 * This class is needed in order to run the observer pattern with threads.
 */
public class GetTheStock implements Runnable {

    //private int startTime;
    private String stock;
    private double price;
    private Subject stockGrabber;

    public GetTheStock(Subject stockGrabber, int startTime, String stock, double price) {

        this.stockGrabber = stockGrabber;
        //this.startTime = startTime;
        this.stock = stock;
        this.price = price;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++){
            try {
                // Thread sleeps for 2 seconds
                Thread.sleep(2000);

                // Use Thread.sleep(startTime * 1000); to
                // make sleep time variable
            }
            catch (InterruptedException e){ }

            double randNum = (Math.random() * (.06)) - 0.03;

            DecimalFormat df = new DecimalFormat("#.##");

            /**
             * The following 3 lines are needed in order to be able to print with commas.
             * Another solution is to use DecimalFormat("#") and not show the commas.
             */
            DecimalFormatSymbols dfs = new DecimalFormatSymbols();
            dfs.setDecimalSeparator('.');
            df.setDecimalFormatSymbols(dfs);

            price = Double.valueOf(df.format((price + randNum)));

            if (stock == "IBM") ((StockGrabber) stockGrabber).setIBMPrice(price);
            if (stock == "AAPL") ((StockGrabber) stockGrabber).setAAPLPrice(price);
            if (stock == "GOOG") ((StockGrabber) stockGrabber).setGOOGPrice(price);

            System.out.println(stock + ": " + df.format((price + randNum)) + "  " + df.format(randNum));
            System.out.println("-------------------");
            System.out.println();

        }
    }
}
